<template>
  <div class="chart-container">
    <div ref="chartRef" style="width: 100%; height: 100vh;"></div>
    <canvas ref="canvasRef" style="position: absolute; top: 0; left: 0; pointer-events: none;"></canvas>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import chinaMap from '@/assets/china.json';

export default {
  name: 'EChartsMap',
  data() {
    return {
      chartInstance: null,
      canvasCtx: null,
      particles: [],
      lastTime: 0,
      animationFrameId: null,
      provinceData: [
        { name: "北京市", value: 21540000 },
        { name: "天津市", value: 15620000 },
        { name: "河北省", value: 75200000 },
        { name: "山西省", value: 37290000 },
        { name: "内蒙古自治区", value: 24720000 },
        { name: "辽宁省", value: 43590000 },
        { name: "吉林省", value: 27340000 },
        { name: "黑龙江省", value: 38000000 },
        { name: "上海市", value: 24150000 },
        { name: "江苏省", value: 80500000 },
        { name: "浙江省", value: 57370000 },
        { name: "安徽省", value: 63430000 },
        { name: "福建省", value: 41330000 },
        { name: "江西省", value: 46480000 },
        { name: "山东省", value: 100700000 },
        { name: "河南省", value: 96050000 },
        { name: "湖北省", value: 59020000 },
        { name: "湖南省", value: 66440000 },
        { name: "广东省", value: 113460000 },
        { name: "广西壮族自治区", value: 49260000 },
        { name: "海南省", value: 9300000 },
        { name: "重庆市", value: 32050000 },
        { name: "四川省", value: 83000000 },
        { name: "贵州省", value: 36000000 },
        { name: "云南省", value: 48000000 },
        { name: "西藏自治区", value: 3400000 },
        { name: "陕西省", value: 38320000 },
        { name: "甘肃省", value: 26000000 },
        { name: "青海省", value: 6000000 },
        { name: "宁夏回族自治区", value: 6800000 },
        { name: "新疆维吾尔自治区", value: 24400000 },
        { name: "台湾省", value: 23600000 },
        { name: "香港特别行政区", value: 7500000 },
        { name: "澳门特别行政区", value: 680000 },
        { name: "南海诸岛", value: 680000 }
      ]
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.resizeHandler);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeHandler);
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
    }
  },
  methods: {
    initChart() {
      try {
        echarts.registerMap('china', chinaMap);
        this.chartInstance = echarts.init(this.$refs.chartRef);

        // 初始化canvas
        const canvas = this.$refs.canvasRef;
        canvas.width = this.$refs.chartRef.clientWidth;
        canvas.height = this.$refs.chartRef.clientHeight;
        this.canvasCtx = canvas.getContext('2d');

        // 加载橘子图片
        this.orangeImg = new Image();
        this.orangeImg.src = '';

        const option = {
          title: {
            text: '中国各省蜜橘分布',
            left: 'center',
            textStyle: {
              color: '#FF7F00',
              fontSize: 22,
              fontWeight: 'bold',
              fontFamily: 'KaiTi, STKaiti, 楷体, 宋体, sans-serif',
              textShadow: '0 2px 4px rgba(255, 165, 0, 0.3)'
            },
          },
          tooltip: {
            trigger: 'item',
            formatter: '{b}<br/>人数: {c}个'
          },
          visualMap: {
            min: 0,
            max: 120000000,
            text: ['高', '低'],
            calculable: true,
            inRange: {color: ['#FFE4B5', '#FFA500', '#FF4500']}
          },
          series: [{
            name: '中国地图',
            type: 'map',
            map: 'china',
            roam: false,
            zoom: 1.2,
            label: {
              show: true,
              color: '#333',
              fontSize: 10
            },
            emphasis: {
              label: {
                color: '#FF1493',
                fontWeight: 'bold'
              },
              itemStyle: {
                areaColor: '#FFB6C1',
                borderColor: '#DB7093',
                borderWidth: 1,
                shadowColor: 'rgba(255, 20, 147, 0.5)',
                shadowBlur: 10
              }
            },
            select: {
              label: {
                color: '#C71585'
              },
              itemStyle: {
                areaColor: '#FF69B4',
                borderColor: '#FF1493',
                borderWidth: 2
              }
            },
            data: this.provinceData
          }]
        };

        this.chartInstance.setOption(option);

        // 添加点击事件
        this.chartInstance.on('click', (params) => {
          this.createOrangeEffect(params.event.event.offsetX, params.event.event.offsetY);
        });

        // 开始动画循环
        this.animate();
      } catch (error) {
        console.error('初始化图表失败:', error);
      }
    },

    // 创建橘子粒子效果
    createOrangeEffect(x, y) {
      const particleCount = Math.floor(Math.random() * 10) + 15; // 15-25个橘子

      for (let i = 0; i < particleCount; i++) {
        this.particles.push({
          x: x,
          y: y - 20, // 从稍高的位置落下
          size: Math.random() * 15 + 10, // 10-25px大小
          speedX: (Math.random() - 0.5) * 8, // 水平速度
          speedY: Math.random() * -5 - 5, // 垂直速度(向上)
          gravity: 0.2,
          rotation: Math.random() * Math.PI * 2, // 随机旋转角度
          rotationSpeed: (Math.random() - 0.5) * 0.2, // 旋转速度
          alpha: 1,
          decay: Math.random() * 0.02 + 0.01 // 透明度衰减
        });
      }
    },

    // 动画循环
    animate(timestamp = 0) {
      if (!this.lastTime) this.lastTime = timestamp;
      const deltaTime = timestamp - this.lastTime;
      this.lastTime = timestamp;

      this.updateParticles(deltaTime);
      this.drawParticles();

      this.animationFrameId = requestAnimationFrame(this.animate);
    },

    // 更新粒子状态
    updateParticles(deltaTime) {
      const canvas = this.$refs.canvasRef;

      for (let i = this.particles.length - 1; i >= 0; i--) {
        const p = this.particles[i];

        // 更新位置
        p.x += p.speedX;
        p.y += p.speedY;

        // 应用重力
        p.speedY += p.gravity;

        // 更新旋转
        p.rotation += p.rotationSpeed;

        // 更新透明度
        p.alpha -= p.decay;

        // 移除不可见的粒子
        if (p.alpha <= 0 || p.y > canvas.height) {
          this.particles.splice(i, 1);
        }
      }
    },

    // 绘制粒子
    drawParticles() {
      const canvas = this.$refs.canvasRef;
      const ctx = this.canvasCtx;

      // 清除画布
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 绘制所有粒子
      for (const p of this.particles) {
        ctx.save();
        ctx.globalAlpha = p.alpha;
        ctx.translate(p.x, p.y);
        ctx.rotate(p.rotation);

        // 绘制橘子(使用图片或绘制圆形)
        if (this.orangeImg.complete) {
          ctx.drawImage(
            this.orangeImg,
            -p.size / 2, -p.size / 2,
            p.size, p.size
          );
        } else {
          // 如果图片未加载，绘制简单的橙色圆形
          ctx.beginPath();
          ctx.arc(0, 0, p.size / 2, 0, Math.PI * 2);
          ctx.fillStyle = '#FF8C00';
          ctx.fill();
          ctx.strokeStyle = '#E67E00';
          ctx.stroke();
        }

        ctx.restore();
      }
    },

    resizeHandler() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
      const canvas = this.$refs.canvasRef;
      if (canvas) {
        canvas.width = this.$refs.chartRef.clientWidth;
        canvas.height = this.$refs.chartRef.clientHeight;
      }
    }
  }
};
</script>

<style scoped>
.chart-container {
  position: relative;
  width: 100%;
  height: 100%;
}

canvas {
  z-index: 10;
}
</style>
